<template>
  <div :class="type == 1 ? 'login-method h340' : 'login-method'">
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="账号登录" name="pwd">
        <div class="pwd">
          <el-form
            :model="pwdForm"
            :rules="pwdFormRules"
            ref="pwdFormRef"
            class="pwd_form"
          >
            <el-form-item prop="phone">
              <el-input placeholder="手机号" v-model="pwdForm.phone">
                <div slot="prefix" class="phone_icon"></div>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                placeholder="密码"
                @keyup.enter.native="login('pwdFormRef')"
                type="password"
                v-model="pwdForm.password"
              >
                <div slot="prefix" class="pwd_icon"></div>
              </el-input>
            </el-form-item>
          </el-form>
          <div class="agreement clearfloat">
            <template v-if="type == 2">
              <div class="clearfloat mt10">
                <el-checkbox v-model="autoLogin" class="fl autoLogin"
                  >自动登录</el-checkbox
                >
                <el-button
                  type="text"
                  class="fr forgot_word ml10"
                  @click="forgotPassword(5)"
                  >忘记密码</el-button
                >
                <el-button type="text" class="fr register_now" @click="register"
                  >立即注册</el-button
                >
              </div>
            </template>
            <template v-else>
              <el-checkbox v-model="autoLogin" class="fl autoLogin">自动登录</el-checkbox>
              <el-button
                type="text"
                class="fr forgot_word ml10"
                @click="forgotPassword(2)"
                >忘记密码</el-button
              >
              <!-- <el-button type="text" class="fr register_now" v-no-more-click:3000 @click="register">立即注册</el-button> -->
            </template>
          </div>
          <el-button
            type="primary"
            @click="login('pwdFormRef')"
            class="login"
            :disabled="!isRead"
            v-no-more-click:3000
            >登录</el-button
          >
          <el-button
            class="application"
            v-if="type == 2"
            @click="$router.push('/user/apply')"
            v-no-more-click:3000
            >快速申请</el-button
          >
        </div>
      </el-tab-pane>
      <el-tab-pane label="验证码登录" name="code">
        <div class="code">
          <el-form
            :model="codeForm"
            :rules="codeFormRules"
            ref="codeFormRef"
            class="code_form"
          >
            <el-form-item prop="phone">
              <el-input placeholder="手机号" v-model="codeForm.phone">
                <div slot="prefix" class="phone_icon"></div>
              </el-input>
              <el-button
                class="code_btns"
                type="text"
                @click="getVCode('codeFormRef')"
                :disabled="btnIsDisabled"
                >{{ VCodeText }}</el-button
              >
            </el-form-item>
            <el-form-item prop="code">
              <!-- <el-input placeholder="验证码" v-model="codeForm.code" class="code_input" @keyup.enter.native="codeLogin('codeFormRef')">
                  <div slot="prefix" class="code_icon"></div>
              </el-input>-->
              <sixCaptchaInput
                ref="sixCaptchaInput"
                :code.sync="codeForm.code"
                @updateCode="updateCode"
              />
            </el-form-item>
          </el-form>
          <div class="agreement clearfloat">
            <template v-if="type == 2">
              <el-checkbox class="ml10" v-model="isRead"></el-checkbox>
              <span>我已阅读且同意</span>
              <span class="btns" @click="agreement">
                <span>服务条款及</span>
                <span>隐私协议</span>
              </span>
              <br />
              <el-button
                type="text"
                class="fr forgot_word ml10"
                @click="forgotPassword(5)"
                >忘记密码</el-button
              >
              <el-button
                type="text"
                class="fr register_now"
                v-no-more-click:3000
                @click="register"
                >立即注册</el-button
              >
            </template>
            <template v-else>
              <el-button
                type="text"
                class="fr forgot_word ml10"
                @click="forgotPassword(2)"
                >忘记密码</el-button
              >
              <!-- <el-button type="text" class="fr register_now" v-no-more-click:3000 @click="register">立即注册</el-button> -->
            </template>
          </div>
          <el-button
            type="primary"
            @click="codeLogin('codeFormRef')"
            class="login"
            :disabled="!isRead"
            >登录</el-button
          >
          <el-button
            class="application"
            v-if="type == 2"
            @click="$router.push('/user/apply')"
            >快速申请</el-button
          >
        </div>
      </el-tab-pane>
    </el-tabs>
    <agreement ref="agreement"></agreement>
  </div>
</template>

<script>
import aes from "~/util/aes.js";
import agreement from "./components/agreement";
import sixCaptchaInput from "~/components/sixCaptcha-input";
import axios from "axios";
import { getMyStatistics } from "~/api/user.js";
export default {
  components: {
    agreement,
    sixCaptchaInput,
  },
  data() {
    var validatePhone = function (rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("请输正确的手机号"));
      } else {
        callback();
      }
    };

    return {
      activeName: "pwd",
      codeForm: {
        phone: "",
        code: "",
      },
      pwdForm: {
        phone: "",
        password: "",
      },
      pwdFormRules: {
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      codeFormRules: {
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        code: [{ message: "请输入验证码", trigger: "blur" }],
      },
      isRead: true,
      VCodeText: "发送验证码",
      btnIsDisabled: false,
      autoLogin: true,
    };
  },
  watch: {
    // 自动登录
    autoLogin(newValue, oldValue) {
      if (process.client) {
        window.localStorage.setItem("autoLogin", JSON.stringify(newValue || true));
      }
      if (this.autoLogin) {
        this.rememberPassword = true;
      }
    },
  },
  mounted() {
    this.H_url = this.$store.getters.getH_url;
    this.A_url = this.$store.getters.getA_url;
    // 判断是否从转化平台过来
    if (this.$router.app._route.query && this.$router.app._route.query.key) {
      this.$store.commit("setKey", this.$router.app._route.query.key);
      const key = this.$store.getters.getKey;
      const params = {
        key: this.$store.getters.getKey,
        sertype: 0,
      };
      // 前往登录验证接口
      this.hasKeyToSwitch(params);
    }
    // 记住密码，自动登录 单选框的值拿存起来的
    this.$nextTick(() => {
      if (process.client) {
        this.autoLogin = JSON.parse(window.localStorage.getItem("autoLogin"));
      }
    });
    // 获取记住密码存储的用户账号密码 在用户注册跳转时无需保存记录的账户密码，只需保存注册时的手机号
    if (!this.$route.params.phone && process.client) {
      // 是否自动登录
      if (
        JSON.parse(window.localStorage.getItem("autoLogin")) &&
        window.localStorage.getItem("userInfo")
      ) {
        let userInfo = JSON.parse(aes.Decrypt(window.localStorage.getItem("userInfo")));
        if (userInfo) {
          this.pwdForm.phone = userInfo.user;
          this.pwdForm.password = userInfo.password;
        }
        this.$nextTick(() => {
          this.login("pwdFormRef");
        });
      }
    }
    //注册过来的则设置默认手机号码
    if (this.$route.params.phone) {
      this.pwdForm.phone = this.$route.params.phone;
    }
  },
  computed: {
    type() {
      // return this.$route.query.type;
      return 1;
    },
  },
  methods: {
    // 查看10月是否开启活动 (已废弃)
    // inspectionActivities () {
    //   this.$axios('/api/activity/eleven/activity').then (res => {
    //     if (res.data.code == 200) {
    //       localStorage.setItem('isActivity',JSON.stringify(res.data.data))
    //     } else {
    //       console.log(res.data.message)
    //     }
    //   })
    // },

    inspectionActivities() {
      this.$axios("/api/activityImage").then((res) => {
        if (res.data.code == 200) {
          this.$store.commit("setUserActivities", res.data.data);
        } else {
          console.log(res.data.message);
        }
      });
    },

    async getMyStatistics(params) {
      let data = await getMyStatistics(this.$axios, params);
      if (data.data.status == "success") {
        this.$store.commit("setUserStatistics", data.data.data);
      }
    },
    // 密码登录
    login(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.type == 1) {
            let url = "api/agent/login";
            let params = {
              phone: this.pwdForm.phone,
              password: this.pwdForm.password,
            };
            this.agentLogin(url, params);
          } else if (this.type == 2) {
            let params = {
              username: this.pwdForm.phone,
              password: this.pwdForm.password,
              sertype: 0,
            };
            let url = this.A_url + "/cPasswordGetKey";
            this.userLogin(url, params, "pwd");
          }
        } else {
          return false;
        }
      });
    },
    // 代理人登录
    agentLogin(url, params) {
      this.$axios.post(url, params).then((res) => {
        if (res.data.code == 200) {
          if (res.data.data.user.role_id == 2) {
            
            this.$alert(`信合红谷代理人请到 <a href='https://xinhehonggu.com/login?type=1'>溟宇科惠知识产权服务平台</a> 登录`, "提示", {
              confirmButtonText: "确定",
              dangerouslyUseHTMLString: true,
              center: true,
              type: "warning",
              callback: (action) => {},
            });

          } else if (res.data.data.user.role_id == 9) {
            this.setLoginStatus(res.data.data);

            if (this.$route.query && this.$route.query.routerfrom) {
              this.$router.push(this.$route.query.routerfrom);
            } else {
              this.$router.replace({ path: "/mechanism/home/menu" });
            }
          }
        } else {
          this.$alert(res.data.message, "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "warning",
            callback: (action) => {},
          });
        }
      });
    },
    // 从专利代理端进入转化平台验证
    hasKeyToSwitch(params) {
      var qs = require("qs");
      axios
        .post(this.A_url + "/checkoutLoginType", qs.stringify(params), {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            const params = {
              key: res.data.data.key,
              sertype: 0,
            };
            let url = "api/auth/platform/login";
            this.hasKeyToLogin(url, params);
          } else {
            alert(res.data.data, "提示", {
              confirmButtonText: "确定",
              center: true,
              type: "warning",
              callback: (action) => {},
            });
          }
        });
    },
    // 用户登录获取key
    userLogin(url, params, loginType) {
      // 引入qs解决登录时使用axios请求数据传参时无法正常的获取数据0714
      var qs = require("qs");
      // 获取key值
      axios
        .post(url, qs.stringify(params), {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.$store.commit("setKey", res.data.data.key);
            let key = this.$store.getters.getKey;
            const params = {
              key: res.data.data.key,
              sertype: 0,
              loginMethod: loginType == "pwd" ? 1 : 2,
            };
            let url = "api/auth/platform/login";
            this.hasKeyToLogin(url, params);
          } else {
            this.$alert(res.data.data, "提示", {
              confirmButtonText: "确定",
              center: true,
              type: "warning",
              callback: (action) => {},
            });
          }
        });
    },
    // 用户获取key后进行登录
    hasKeyToLogin(url, params) {
      // 用获取的key进行登录验证
      this.$axios.post(url, params).then((res) => {
        if (res.data.code == 200) {
          this.setLoginStatus(res.data.data);

          this.inspectionActivities();
          if (this.$route.query && this.$route.query.routerfrom) {
            this.$router.push(this.$route.query.routerfrom);
          } else {
            this.$router.push("/user/home/menu");
          }
        } else {
          this.$alert(res.data.message, "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "warning",
            callback: (action) => {},
          });
        }
      });
    },
    // 验证码登录
    codeLogin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.type == 1) {
            let params = {
              phone: this.codeForm.phone,
              code: this.codeForm.code,
            };
            let url = "/api/agent/agentCodeLogin";
            this.agentLogin(url, params);
            this.inspectionActivities();
          } else if (this.type == 2) {
            const params = {
              tel: this.codeForm.phone,
              code: this.codeForm.code,
              sertype: 0,
            };
            const url = this.A_url + "/cTelCodeLogin";
            this.userLogin(url, params, "code");
            this.inspectionActivities();
          }
        } else {
          return false;
        }
      });
    },
    // 设置登录状态
    setLoginStatus(data) {
      // 清除之前的登录状态
      this.$cookies.remove("agent");
      this.$store.commit("delToken");
      this.$cookies.remove("token");
      this.$store.commit("delUser");
      this.$cookies.remove("user");

      if (process.client) {
        sessionStorage.removeItem("store");
        window.localStorage.setItem("autoLogin", JSON.stringify(true));
      }

      this.$cookies.set("token", data.token);
      this.$store.commit("setToken", data.token);
      // cookie 存user 可能会超出限制这里随便拿几个值有user通过路由鉴权就行了
      let cookieUser = {
        id: data.user.id,
        name: data.user.name,
        role_id: data.user.role_id,
      };
      this.$cookies.set("cookiesUser", aes.Encrypt(JSON.stringify(cookieUser)));
      this.$axios.defaults.headers.common["Authorization"] = "Bearer " + data.token;

      this.$store.commit("setUser", data.user);
      if (this.autoLogin) {
        let userInfo = {
          user: this.pwdForm.phone,
          password: this.pwdForm.password,
        };
        this.$cookies.set("userInfo", userInfo);
        if (process.client) {
          window.localStorage.setItem("userInfo", aes.Encrypt(JSON.stringify(userInfo)));
        }
      }
      if (
        data.user.role_id == 5 ||
        data.user.role_id == 9 ||
        data.user.status == "已激活"
      )
        this.getMyStatistics();
    },
    // 获取验证码
    getVCode(formName) {
      this.$refs[formName].validateField("phone", (valid) => {
        if (!valid) {
          if (this.btnIsDisabled) {
          } else {
            this.getVCodeRequest();
          }
        } else {
          return false;
        }
      });
    },
    getVCodeRequest() {
      let that = this;
      if (this.type == 1) {
        let params = {
          phone: this.codeForm.phone,
          type: 2,
          // guard:
        };
        let url = "/api/captcha";
        that.$axios.post(url, params).then((res) => {
          if (res.data.code == 200) {
            that.$message({
              message: "验证码发送成功！",
              type: "success",
            });
            let num = 60;
            that.btnIsDisabled = true;
            let timer = setInterval(function () {
              that.VCodeText = num + "秒后可重新发送";
              num -= 1;
              if (num < 0) {
                that.VCodeText = "发送验证码";
                that.btnIsDisabled = false;
                clearInterval(timer);
              }
            }, 1000);
          } else {
            if (res.data.code == 400) {
              that.$message({
                message: res.data.message,
                type: "error",
              });
            } else {
              that.$message({
                message: "验证码发送失败！",
                type: "error",
              });
            }
          }
        });
      } else if (this.type == 2) {
        const that = this;
        const params = {
          tel: this.codeForm.phone,
          sertype: 0,
        };
        var qs = require("qs");
        axios
          .post(this.A_url + "/cgetTelCodeToLogin", qs.stringify(params), {
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
          })
          .then((res) => {
            if (res.data.code === 200) {
              that.$message({
                message: "验证码发送成功！",
                type: "success",
              });
              let num = 60;
              that.btnIsDisabled = true;
              const timer = setInterval(function () {
                that.VCodeText = num + "秒后可重新发送";
                num -= 1;
                if (num < 0) {
                  that.VCodeText = "发送验证码";
                  that.btnIsDisabled = false;
                  clearInterval(timer);
                }
              }, 1000);
            } else {
              if (res.data.code === 301) {
                that.$message({
                  message: res.data.data,
                  type: "error",
                });
              } else {
                that.$message({
                  message: "验证码发送失败！",
                  type: "error",
                });
              }
            }
          });
      }
    },
    // 打开协议
    agreement() {
      this.$refs["agreement"].isShow = true;
    },
    // 立即注册
    register() {
      if (this.type == 1) {
        // this.$router.push('/agentRegister')
      } else if (this.type == 2) {
        this.$router.push("/register");
      }
    },
    // 忘记密码
    forgotPassword(type) {
      // 跳转忘记密码页面
      this.$router.push({
        path: "/forgotPassword",
        query: {
          type: type,
        },
      });
    },
    updateCode(val) {
      this.codeForm.code = val;
    },
  },
};
</script>

<style lang="less">
.login-method {
  width: 549px;
  height: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 1);

  .el-tabs {
    width: 100%;
    height: 100%;

    .el-tabs__header {
      border: none;
      margin: 0;
      .el-tabs__nav-scroll {
        .el-tabs__nav {
          width: 100%;
          border: none;
          .el-tabs__item {
            width: 50%;
            text-align: center;
            border: none;
            font-size: 15px;

            color: #fff;
            background: rgba(36, 157, 255, 1);
          }
          .is-active {
            color: rgba(36, 157, 255, 1);
            background: #fff;
          }
        }
      }
    }

    .el-form {
      width: 390px;
      margin: 45px auto 10px;

      .el-form-item {
        margin-bottom: 30px;
        position: relative;
      }
      .el-input {
        .el-input__inner {
          padding-left: 58px;
        }
        .el-input__prefix {
          left: 20px;
        }
      }
    }
    .pwd {
      .pwd_form {
        .el-form-item:last-child {
          margin-bottom: 10px;
          .el-form-item__error {
            padding-top: 1px;
          }
        }
        .phone_icon {
          width: 16px;
          height: 26px;
          background: url("../../assets/img/图标.png") no-repeat;
          background-position: -371px -419px;
          margin-top: 6px;
        }
        .pwd_icon {
          width: 17px;
          height: 26px;
          background: url("../../assets/img/图标.png") no-repeat;
          background-position: -458px -396px;
          margin-top: 6px;
        }
      }
    }
    .code {
      .code_form {
        .el-form-item:last-child {
          margin-bottom: 10px;
          .el-form-item__error {
            padding-top: 1px;
          }
        }

        .code_btns {
          position: absolute;
          right: 18px;
          bottom: 0px;
        }
        .phone_icon {
          width: 16px;
          height: 26px;
          background: url("../../assets/img/图标.png") no-repeat;
          background-position: -371px -419px;
          margin-top: 6px;
        }
        .code_icon {
          width: 27px;
          height: 17px;
          background: url("../../assets/img/图标.png") no-repeat;
          background-position: -399px -398px;
          margin-top: 10px;
        }
      }
    }
    .agreement {
      width: 390px;
      margin: 0 auto;
      font-size: 12px;
      color: rgba(36, 157, 255, 1);
      i {
        font-style: normal;
        text-decoration: none;
      }

      .decoration {
        border-bottom: 1px dashed rgba(36, 157, 255, 1);
      }
      .btns {
        cursor: pointer;
      }

      .register_now {
        padding: 0;
        font-size: 12px;
        line-height: normal;
      }
      .forgot_word {
        padding: 0;
        font-size: 12px;
        line-height: normal;
      }
      .autoLogin {
        .el-checkbox__label {
          font-size: 12px;
          color: rgba(36, 157, 255, 1);
        }
      }
    }
    .login {
      width: 390px;
      margin: 30px auto 0;
      display: block;
    }
    .application {
      width: 390px;
      margin: 20px auto 0;
      display: block;
      border: 1px solid rgba(88, 165, 234, 1);
      color: rgba(36, 157, 255, 1);
    }
  }
}
.h340 {
  height: 340px;
}
</style>
